package com.mx.nbainformation.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

import android.content.Context;
import android.gesture.Prediction;

import com.mx.nbainformation.Model.MonthData;
import com.mx.nbainformation.Model.NewsListData;
import com.mx.nbainformation.config.ConstantUrls;
import com.mx.nbainformation.config.Constants;
import com.mx.nbainformation.util.FileUtil;
import com.mx.nbainformation.util.HttpUtil;

public class BizNews {
	public static String NewsWeb = "";
	public static String PREVIOUS="previous";
	public static String NEXT="next";

	private Context _context;

	public BizNews(Context context) {
		_context = context;
	}
	
	public String getUrl(Boolean isPrevious,Boolean isNext)
	{
		String Address = null;
		if (isPrevious) {
			if(NewsWeb==null)return null;
			String strPreviousUrl=String.format(Constants.PreviousUrl,PREVIOUS );
			Matcher mprovious=FileUtil.getPattern(strPreviousUrl, NewsWeb);
			if(!mprovious.find())return null;
			Address=mprovious.group();
			Address=Address.replaceAll(String.format(Constants.PreviousReplace1,PREVIOUS), "");
			Address=Address.replaceAll(Constants.PreviousReplace2, "");
		} else if (isNext) {
			if(NewsWeb==null)return null;
			String strPreviousUrl=String.format(Constants.PreviousUrl,NEXT );
			Matcher mprovious=FileUtil.getPattern(strPreviousUrl, NewsWeb);
			if(!mprovious.find())return null;
			Address=mprovious.group();
			Address=Address.replaceAll(String.format(Constants.PreviousReplace1,NEXT), "");
			Address=Address.replaceAll(Constants.PreviousReplace2, "");
		} else if (!isNext && !isPrevious) {
			Address = ConstantUrls.NewsDefaultUrl;
		}
		return Address;
	}
	
	public List<Map<String, Object>> getNewsList(String url) {
		NewsWeb = HttpUtil.doGet(url, _context);
		if(NewsWeb==null)return null;
		Matcher m = FileUtil.getPattern(Constants.NewsSpan, NewsWeb);
		if (!m.find())
			return null;
		String newsSpan = m.group();
		Matcher everyNews = FileUtil.getPattern(Constants.EveryNews, newsSpan);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		int id = 0;
		while (everyNews.find()) {
			String date = everyNews.group().replaceAll(Constants.EveryNewsReplace1, "");
			date = date.replaceAll(Constants.EveryNewsReplace2, "aabbccdd");
			date = date.replaceAll(Constants.EveryNewsReplace3, "aabbccdd");
			date=date.replaceAll(Constants.EveryNewsReplace4, "");
			String[] items = date.split("aabbccdd");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put(NewsListData.ID, id);
			map.put(NewsListData.TARGER,items[0]);
			map.put(NewsListData.CONTENT, items[1]);
			map.put(NewsListData.NEWSDATE, items[2]);
			list.add(map);
			id++;
		}
		return list;
	}
}
